// components/search/index.js
import {
  KeywordModel
} from "../../models/Keyword.js";

import {
  BookModel
} from "../../models/Book.js";

import {
  paginationBev
} from "../../components/behaviors/pagination.js";

const keywordModel = new KeywordModel();
const bookModel = new BookModel();

Component({
  behaviors: [paginationBev],
  /**
   * 组件的属性列表
   */
  properties: {
    more: {
      type: String,
      observer: "loadMore"
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    historyWords: [],
    hotWords: [],
    searching: false, //是否显示搜索结果
    q: "",
    loadingCenter:false,
  },

  attached: function () {
    const keywords = keywordModel.getHistory();
    const hotWords = keywordModel.getHot();
    this.setData({
      historyWords: keywords,
    });
    hotWords.then(res => {
      // console.log(res);
      this.setData({
        hotWords: res.hot,
      });
    });
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onCancel: function (event) {
      this.initialize();
      this.triggerEvent("searchCancel", {}, {});
    },
    onDelete: function () {
      this.initialize();
      this.setData({
        searching: false,
        q: '',
      });
    },
    onConfirm: function (event) {
      this._showResult();
      this._showLoadingCenter();
      //清空上一次搜索的数据
      this.initialize();
      //一个是用户输入的，一个是用户点击标签的
      const val = event.detail.value || event.detail.text;
      this._setInputVal(val);
      bookModel.search(0, val).then(res => {
        //设置数据
        this.setMoreData(res.books);
        // 设置total
        this.setTotal(res.total);
        //添加到历史记录缓存
        keywordModel.addToHistory(val);
        this._hideLoadingCenter();
      });
    },
   
    loadMore: function () {
      if (!this.data.q) {
        return;
      }
      if (this.isLocked()) {
        return;
      }
      if (this.hasMore()) {
        this.locked(); //将锁锁上
        bookModel.search(this.getCurrentStart(), this.data.q).then(res => {
          //添加数据
          this.setMoreData(res.books);
          //获取到数据后将锁打开
          this.unlock();
        },()=>{
          this.unlock();
        });
      }
    },
     //进入搜索结果的视图
     _showResult() {
      this.setData({
        searching: true,
      });
    },
    //显示中间的加载进度框
    _showLoadingCenter(){
      this.setData({
        loadingCenter:true,
      });
    },
    _hideLoadingCenter(){
      this.setData({
        loadingCenter:false
      });
    },

    //显示底部的下拉加载进度框
    _showLoadingMore(){
      this.setData({
        loadingMore: true,
      });
    },
    _hideLoadingMore(){
      this.setData({
        loadingMore: false,
      });
    },
    //回显搜索框
    _setInputVal(val){
      this.setData({
        q: val,
      });
    }
  }
})